var express = require('express');
var router = express.Router();
var sql = require('../db/index')



/**
 * @swagger
 *   /dingdan/saveOrUpdate:
 *   post:
 *     description: 新增或编辑订单信息
 *     tags: [订单]
 *     produces:
 *       - application/x-www-form-urlencoded
 *     parameters:
 *       - name: id
 *         description: 订单id（编辑时需要）
 *         required: false
 *         type: number
 *       - name: customer_name
 *         description: 客户姓名
 *         required: true
 *         type: string
 *       - name: product
 *         description: 订单产品
 *         required: true
 *         type: string
 *       - name: quantity
 *         description: 订单数量
 *         required: true
 *         type: number
 *       - name: status
 *         description: 订单状态
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: 操作成功
 *       500:
 *         description: 服务器错误
 */

// 新增或编辑接口
router.post('/saveOrUpdate', async (req, res) => {
  const { id, customer_name, product, quantity, status } = req.body;
  let mysql = '';
  if (id) {
    mysql = `UPDATE jz_dingdan SET customer_name = '${customer_name}', product = '${product}', quantity = ${quantity}, status = '${status}' WHERE id = ${id}`;
  } else {
    mysql = `INSERT INTO jz_dingdan (id, customer_name, product, quantity, status) VALUES (null, '${customer_name}', '${product}', ${quantity}, '${status}')`;
  }
  await sql.query(mysql);
  res.send({
    status: 200,
    message: "操作成功",
    data: null,
    timestamp: new Date().getTime()
  });
});

/**
 * @swagger
 *   /dingdan/delete:
 *   post:
 *     description: 删除订单信息
 *     tags: [订单]
 *     produces:
 *       - application/x-www-form-urlencoded
 *     parameters:
 *       - name: id
 *         description: 订单id
 *         required: true
 *         type: number
 *     responses:
 *       200:
 *         description: 删除成功
 *       500:
 *         description: 服务器错误
 */

// 删除接口
router.post('/delete', async (req, res) => {
  const { id } = req.body;
  const mysql = `DELETE FROM jz_dingdan WHERE id = ${id}`;
  await sql.query(mysql);
  res.send({
    status: 200,
    message: '删除成功',
    data: null,
    timestamp: new Date().getTime()
  });
});

/**
 * @swagger
 *   /dingdan/get:
 *   get:
 *     description: 获取订单信息
 *     tags: [订单]
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: id
 *         description: 订单id
 *         required: false
 *         type: number
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器错误
 */

// 查询接口
router.get('/get', async (req, res) => {
  const { id } = req.query;
  let mysql = '';
  if (id) {
    mysql = `SELECT * FROM jz_dingdan WHERE id = ${id}`;
  } else {
    mysql = `SELECT * FROM jz_dingdan`;
  }
  const results = await sql.query(mysql);
  res.send({
    status: 200,
    message: '获取成功',
    data: results,
    timestamp: new Date().getTime()
  });
});

module.exports = router;

